<template>
  <el-form
    ref="smsLoginForm"
    :model="smsFormData"
    status-icon
    :rules="smsRules"
    label-width="120px"
    class="demo-smsFormData"
  >
    <div class="common-login">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="smsFormData.phone" maxlength="11" class="phone" />
        <span @click="sendSms">{{ desc }}</span>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="smsFormData.code" type="text" autocomplete="off" />
      </el-form-item>

      <el-form-item id="button">
        <el-button type="primary" @click="submitForm(smsLoginForm)">
          提交
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup>
import { reactive, ref, onUnmounted } from "vue";
import { smsRules, userSubmitForm } from "../../composition/login/validate";
import * as api from "@/api/users";
//引入路由对象
import { useRouter } from "vue-router";
//引入elementPlus消息提示
import { ElMessage } from "element-plus";
//引入store
import { useUser } from "@/store/users.js";
//引入loading动画加载
import { ElLoading } from "element-plus";
let userStore = useUser();
let router = useRouter();
//表单校验成功之后，回调的方法
let validateSuccess = async () => {
  // console.log("校验成功");
  //发起loading加载
  let loadingInstance = ElLoading.service({
    text: "正在登入...",
    background: "rgba(0,0,0,0.4)",
  });

  //发起短信登入请求
  try {
    let res = await api.smsApi(smsFormData.code);

    //存token
    sessionStorage.setItem("qf-token", res.data.token);
    //存储用户信息
    userStore.$patch({ userInfo: res.data.userInfo });
    // console.log(res);
    router.push("/");
  } catch (e) {
    console.log(e);
    //关闭loading加载
    loadingInstance.close();
  }
};
//表单校验失败之后，回调的方法
let validateFailed = () => {
  console.log("校验失败");
};
let submitForm = userSubmitForm(validateSuccess, validateFailed);

const smsLoginForm = ref();

const smsFormData = reactive({
  phone: "",
  code: "",
});
//短信登入流程
//1.输入手机号，点击发送按钮，获取短信验证码
//短信验证码需要进行倒计时提示
//2.输入短信验证码，进入登录请求

//声明变量改变span中间的文字
let desc = ref("点击发送");
let timeDownInterval = null;
//避免用户频繁操作，应用开关思路,初始值用户未点击
let isClick = false;
let sendSms = async () => {
  if (!isClick) {
    //发起获取短信验证码请求
    try {
      let res = await api.getSmsCodeApi(smsFormData.phone);
      //成功消息提示
      ElMessage({
        message: "短信验证码发送成功",
        type: "success",
      });
      // console.log(res);
      //调用倒计时方法
      timeDownInterval = timeDown(20, desc, "s后重新发送", desc.value, () => {
        isClick = false;
      });
    } catch (e) {
      console.log(e);
      isClick = false;
      //失败消息提示
      ElMessage({
        message: e,
        type: "error",
      });
      return;
    }
  }

  isClick = true;
};

//短信倒计时方法
/**
 * @param {Number} timer 倒计时的时间
 * @param {Object} param 需要变更的响应式变量
 * @param {String} msg 倒计时秒数的文字
 * @param {String} endMsg 倒计时结束后，回显的文字
 * @param {Function} cd 倒计时结束后回调的函数
 */
//核心：间隔定时器
//字符串.padStart("希望几位数"，用什么字符去补)

let timeDown = (timer = 5, param, msg, endMsg, cd) => {
  let count = timer;
  param.value = (count + "").padStart(2, 0) + msg;
  let interval = setInterval(() => {
    count--;
    // console.log(count);
    if (count <= 0) {
      clearInterval(interval);

      param.value = endMsg;
      cd && cd();
      return;
    }
    param.value = (count + "").padStart(2, 0) + msg;
  }, 1000);

  return interval;
};
//组件卸载时，如果定时器存在，需要清除定时器
onUnmounted(() => {
  if (timeDownInterval) clearInterval(timeDownInterval);
  //关闭loading加载
  loadingInstance && loadingInstance.close();
});
</script>
<style lang="less" scoped>
.common-login {
  padding-right: 50px;

  .el-form-item {
    margin-bottom: 20px;
    height: 44px;
    span {
      background: #fff;
      display: inline-block;
      height: 44px;
      width: 125px;
      text-align: center;
      line-height: 44px;
      cursor: pointer;
      border: 0;
      border-radius: 0 5px 5px 0;
      color: #666;
      font-size: 14px;
      text-decoration: underline;
    }
    :deep(.el-form-item__label) {
      color: #fff;
      width: 100px !important;
      text-align: right;
      vertical-align: middle;
      float: left;
      font-size: 14px;
      line-height: 44px;
      padding: 0 12px 0 0;
      box-sizing: border-box;
    }

    .el-button {
      width: 250px;
      height: 44px;
      background: linear-gradient(90deg, #1596fb, #002dff);
      display: inline-block;
      line-height: 1;
      //   white-space: nowrap;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      text-align: center;
      box-sizing: border-box;
      outline: 0;
      margin: -20px;
      //   transition: 0.1s;
      font-weight: 500;
      padding: 12px 20px;
      font-size: 14px;
      border-radius: 4px;
    }
  }
}

.el-form-item__content {
  margin-left: 120px !important;
  line-height: 44px;
  position: relative;
  font-size: 14px;
  .el-input {
    width: 250px;
    height: 44px;
    border-radius: 5px;
    position: relative;
    font-size: 14px;
    display: inline-block;
    :deep(.el-input__wrapper) {
      width: 100%;
      padding: 0;
      margin: 0;
      height: 44px !important;
      box-shadow: 0 0 0 0;
    }
  }
  .phone {
    width: 125px;
    vertical-align: top;
    :deep(.el-input__wrapper) {
      border-right: 0 !important;
      border-radius: 5px 0 0 5px;
    }
  }
  span {
    background: #fff;
    display: inline-block;
    height: 45px;
    width: 150px;
    text-align: center;
    cursor: pointer;
    border: 0;
    border-radius: 0 5px 5px 0;
  }
}
</style>
